import React, { Component } from 'react';
import { routerRedux, Route, Switch } from 'dva/router';

import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button, Menu, Dropdown, Icon, Row, Col,
  Input, InputNumber,
  Steps, Card, Popover, Badge, Table, Tooltip, Divider,
  Checkbox, Modal, Radio,
  Select, Upload, message, Form

} from 'antd';
import { getRoutes } from '../../utils/utils';
import classNames from 'classnames';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ApplyProfile.less';
import u620 from '../../assets/u620.png';
import u622 from '../../assets/u622.png';
import yes from '../../assets/yes.png';
import no from '../../assets/no.png';
import querystring from 'querystring';
const { Step } = Steps;
const TextArea = Input.TextArea;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;

const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);


@connect(({ pendingTask, }) => ({
  pendingTask,
}))
export default class ApplyDetails4 extends Component {
  state = {
    id: '',
    taskId: '',
    operationkey: 'tab1',
    stepDirection: 'horizontal',
    modalVisible: false,
    previewVisible: false,
    previewImage: '',
    dispatchOne: false,
    reviewState: '',
    inComeValue: '',
    inComeValueStart: '',
    inComeValueEnd: '',
    dispatchTwo: false,
    dispatchThree: false,
    profileState4: null,
    custTaskListLoading: false,
    // incomeResult: 0,
    familyIncome:'',
    note:'',
    other:'',
    otherNote:'',
    estate:'',
    fileList: {      
      incomeVerify: [],
    },
    imageRotateDeg: 0,
    enlarge:1,
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    // console.log("qqqqqAAAAAAAAparams.id")
    // console.log(params.custId)
    this.setState({
      id: params.custId,
      taskId: params.taskId,
      reviewState: params.reviewState,
    })
    if(params.reviewState == 1){
      this.setState({        
        dispatchdOne: false
      })
    }else if(params.reviewState == 2){
      this.setState({
        dispatchOne: true,
        dispatchTwo: false
      })
    }else if(params.reviewState == 3){
      this.setState({
        dispatchOne: true,
        dispatchTwo: true,
        dispatchThree: true
      })
    }
    // console.log("custTaskList",params.custId)
    if (params.custId != null) {
      dispatch({
        type: 'pendingTask/queryAbility',
        payload: {
          id: params.custId,         
        },
        
        callback:()=>{
          const { pendingTask: {abilityList} } = this.props;
          console.log(abilityList)
          let idcardFileList = this.state.fileList;
          let idcardVerifyFileList = abilityList;
          if(idcardVerifyFileList){
            if (idcardVerifyFileList.incomeVerify.images.length > 0) {
              for (let i = 0; i < idcardVerifyFileList.incomeVerify.images.length; i++) {
                idcardFileList.incomeVerify.push({
                  uid: idcardVerifyFileList.incomeVerify.images[i],
                  name: 'xxx.png',
                  status: 'done',
                  url: idcardVerifyFileList.incomeVerify.images[i],
                })
              }
            }
          }
          
          abilityList.incomeVerify&&
          this.setState({          
            inComeValueStart: abilityList.incomeVerify.verifyResult.audit1,
            inComeValueEnd: abilityList.incomeVerify.verifyResult.audit2,
            fileList: idcardFileList,
            familyIncome: abilityList.incomeVerify.familyIncome,
            note: abilityList.incomeVerify.note,
            other: abilityList.debtVerify.other,
            otherNote: abilityList.debtVerify.note,
            estate: abilityList.estate,
          })
        }
      });
    }

    this.setStepDirection();
    window.addEventListener('resize', this.setStepDirection);
  }

  // componentWillUnmount() {
  //   window.removeEventListener('resize', this.setStepDirection);
  //   this.setStepDirection.cancel();
  // }

  onOperationTabChange = (key) => {
    this.setState({ operationkey: key });
  }

  @Bind()
  @Debounce(200)
  setStepDirection() {
    const { stepDirection } = this.state;
    const w = getWindowWidth();
    if (stepDirection !== 'vertical' && w <= 576) {
      this.setState({
        stepDirection: 'vertical',
      });
    } else if (stepDirection !== 'horizontal' && w > 576) {
      this.setState({
        stepDirection: 'horizontal',
      });
    }
  }

  handleClickShowAttachments() {
    this.setState({
      modalVisible: true,
    });
  }

  handleModalOk() {
    this.setState({
      modalVisible: false,
    });
  }
  handleModalCancel() {
    this.setState({
      modalVisible: false,
    });
  }

  handleClickSubmit = () => {
    
    this.setState({
      custTaskListLoading: true
    })
    if(this.state.reviewState == 1){
          this.props.dispatch({
            type: 'pendingTask/commitAbility',
            payload: {
              taskId: this.state.taskId,
              verifyResult: this.state.inComeValueStart,
              familyIncome: this.state.familyIncome,
              incomeNote: this.state.note,
              otherDept: this.state.other,
              deptNote: this.state.otherNote,
              estate: this.state.estate,
            },
            callback: () => {
                     
              const { pendingTask: { custTaskListLoading, auditStatusList } } = this.props;
              this.setState({
                custTaskListLoading: custTaskListLoading
              })         
              const newAuditStatusList = [...auditStatusList];
              newAuditStatusList[3] = true;
              this.props.dispatch({
                type: 'pendingTask/changeApplyDetailsState1',
                payload: newAuditStatusList,
              })
            }
          })
    }
    if(this.state.reviewState == 2 ){
          this.props.dispatch({
            type: 'pendingTask/commitAbility',
            payload: {
              taskId: this.state.taskId,
              familyIncome: this.state.familyIncome,
              incomeNote: this.state.note,
              otherDept: this.state.other,
              deptNote: this.state.otherNote,
              estate: this.state.estate,
              verifyResult: this.state.inComeValueEnd
            },
            callback: () => {
                     
              const { pendingTask: { custTaskListLoading, auditStatusList } } = this.props;
              this.setState({
                custTaskListLoading: custTaskListLoading
              })         
              const newAuditStatusList = [...auditStatusList];
              newAuditStatusList[3] = true;
              this.props.dispatch({
                type: 'pendingTask/changeApplyDetailsState1',
                payload: newAuditStatusList,
              })
            }
          })
    }
      
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
      imageRotateDeg: 0,
    });
  }

  // handleChange = ({ fileList }) => this.setState({ fileList })

  handleInComeValueStart = (e) => {
    this.setState({
      inComeValueStart: e.target.value
    })
  }
  handleInComeValueEnd = (e) => {
    this.setState({
      inComeValueEnd: e.target.value
    })
  }
  handleFamilyIncome = (value) => {
    this.setState({
      familyIncome: value
    })
  }
  handleNote = (e) => {
    this.setState({
      note: e.target.value
    })
  }
  handleOther = (value) => {
    this.setState({
      other: value
    })
  }
  handleOtherNote = (e) => {
    this.setState({
      otherNote: e.target.value
    })
  }
  handleEstate = (e) => {
    this.setState({
      estate: e.target.value
    })
  }
  handleRotate = () => {
    this.setState({
      imageRotateDeg: this.state.imageRotateDeg + 90,
    });
  }
  handleAmplification = () => {
    if (this.state.enlarge >= 2) {
      message.warning("不能再放大了")
    } else {
      this.setState({
        enlarge: this.state.enlarge * 2,
      })
    }
  }
  handleNarrow = () => {
    if (this.state.enlarge <= 1) {
      message.warning("不能再缩小了")
    } else {
      this.setState({
        enlarge: this.state.enlarge * 0.5,
      })
    }
  }

  render() {
    const { stepDirection, previewImage, previewVisible } = this.state;
    const { pendingTask: {abilityList} } = this.props;
    const imgWidth = 500 * this.state.enlarge;
    const imgHeight = 500 * this.state.enlarge;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    // console.log("JSON.stringify(abilityList)" )
    // console.log(JSON.stringify(abilityList) )

    return (
      // abilityList &&
      <Row>
        <Row>
          <Col span={21}>
            <Card
              title="收入水平核实"
              bordered={false}
              style={{ marginBottom: 24 }}
            >
              
              <Row>
                <DescriptionList className={styles.headerList} size="small" col="2">
                  <Description term="申请人月收入">
                  {abilityList.incomeVerify && abilityList.incomeVerify.major}
                  </Description>
                  
                    <Description term="共还月收入">
                    {abilityList.incomeVerify && abilityList.incomeVerify.jointly}
                    </Description>
                </DescriptionList>
              </Row>
              
              <Row style={{ marginTop: 20 }}>
                <DescriptionList className={styles.headerList} size="small" col="1">
                  <Description term="收入证明">
                    <Upload
                      listType="picture-card"
                      fileList={this.state.fileList.incomeVerify}
                      onPreview={this.handlePreview}
                      showUploadList={{ showRemoveIcon: false }}
                    >
                    </Upload>
                  </Description>
                </DescriptionList>
              </Row>
              
              <Row style={{ marginTop: 20 }}>
                <DescriptionList className={styles.headerList} size="small" col="1">
                  <Description term="收入核实初审">
                    <RadioGroup 
                      value={this.state.inComeValueStart}
                      disabled={this.state.dispatchTwo}
                      onChange={this.handleInComeValueStart}>
                      <Radio value={1}>一致</Radio>
                      <Radio value={2}>不同</Radio>
                    </RadioGroup>
                    {this.state.inComeValueStart == 1 ? <img src={yes} /> : null}
                    {this.state.inComeValueStart == 2 ? <img src={no} /> : null}
                  </Description>
                </DescriptionList>
              </Row>
              
              {this.state.reviewState == 1 ?
              null
              :            
              <Row style={{ marginTop: 20 }}>
                <DescriptionList className={styles.headerList} size="small" col="1">
                  <Description term="收入核实复审">
                    <RadioGroup 
                    value={this.state.inComeValueEnd} 
                    disabled={this.state.dispatchTwo}
                    onChange={this.handleInComeValueEnd}
                    >
                      <Radio value={1}>一致</Radio>
                      <Radio value={2}>不同</Radio>
                    </RadioGroup>
                    {this.state.inComeValueEnd == 1 ? <img src={yes} /> : null}
                    {this.state.inComeValueEnd == 2 ? <img src={no} /> : null}
                  </Description>
                </DescriptionList>
              </Row> 
              }
              
                <Row style={{marginTop: 20}}>
                <Col span={4}>
                核实家庭月收入:
                </Col>
                <Col span={12}>
                  <InputNumber disabled={this.state.dispatchTwo} value={this.state.familyIncome} onChange={this.handleFamilyIncome} />                
                </Col>
                </Row>
                <Row style={{marginTop: 20}}>
                <Col span={4}>
                测算依据:
                </Col>
                <Col span={12}>
                  <TextArea rows={4} disabled={this.state.dispatchTwo} placeholder="收入说明" value={this.state.note} onChange={this.handleNote} />          
                </Col>
                </Row>
            </Card>

            <Card
              title="负债情况核实"
              bordered={false}
              style={{ marginBottom: 24 }}
            >
              <Row>
                <DescriptionList className={styles.headerList} size="small" col="1">
                  <Description term="本次分期金额">
                    {abilityList.debtVerify && Number(abilityList.debtVerify.monthPay).toFixed(2) }
                  </Description>
                </DescriptionList>
              </Row>
              <Row style={{ marginTop: 20 }}>
                <Col span={4}>
                  其他负债:
                </Col>
                <Col span={12}>
                  <InputNumber disabled={this.state.dispatchTwo} value={this.state.other} onChange={this.handleOther} />
                </Col>
              </Row>
              <Row style={{ marginTop: 20 }}>
                <Col span={4}>
                  其他负债说明:
                </Col>
                <Col span={12}>
                  <TextArea rows={4} disabled={this.state.dispatchTwo} placeholder="说明"  value={this.state.otherNote} onChange={this.handleOtherNote} />
                </Col>
              </Row>
              <Row>
                <DescriptionList className={styles.headerList} size="small" col="2" style={{ marginTop: 15}}>
                  <Description term="收入还贷比（本业务）">  
                  {this.state.familyIncome && (Number(abilityList.debtVerify.monthPay)/(Number(this.state.familyIncome))*100).toFixed(2)}%
                  </Description>
                  <Description term="收入还贷比（全部）">
                  { this.state.familyIncome && 
                    ( ((Number(abilityList.debtVerify.monthPay) + Number(this.state.other==""?0:this.state.other))/Number(this.state.familyIncome) ) *100).toFixed(2)
                  }%
                  </Description>
                </DescriptionList>
              </Row>

            </Card>

            <Card
              title="资产"
              bordered={false}
              style={{ marginBottom: 24 }}
            >
            
              <Row>
                <Col span={4}>
                  金融资产、不动产、动产情况:
                </Col>
                <Col span={12}>
                  <TextArea disabled={this.state.dispatchTwo} rows={4} placeholder="说明"  value={this.state.estate} onChange={this.handleEstate}/>
                </Col>
              </Row>
              {
                this.state.reviewState == 3 ?
                null
                :
                <p style={{ textAlign: 'left', marginTop: 40 }}>
                  <Button type="primary" onClick={this.handleClickSubmit} >提交</Button>
                </p>
              }
            </Card>
          </Col>
        </Row>
        <Modal
            width={imgWidth + 40}
            visible={previewVisible}
            footer={null}
            onCancel={this.handleCancel}>
            <div style={{ justifyContent: 'space-around', display: 'flex' }}>
              <img alt="example"
                style={{
                  width: imgWidth,
                  height: imgHeight,
                  transform: `rotate(${this.state.imageRotateDeg}deg)`
                }}
                src={previewImage}
              />
            </div>
            <Row type="flex" justify="space-around" style={{
              marginTop: 25,
            }} >
              <Button onClick={this.handleRotate}>旋转</Button>
              <Button onClick={this.handleAmplification}>放大</Button>
              <Button onClick={this.handleNarrow}>缩小</Button>
            </Row>
          </Modal>
      </Row>
      // </PageHeaderLayout>
    );
  }
}
